/* eslint-disable antfu/no-top-level-await */
/* eslint-disable no-console */

import fs from 'node:fs'
import fsp from 'node:fs/promises'
import { createRequire } from 'node:module'
import os from 'node:os'
import path from 'node:path'
import process from 'node:process'

import { cancel, intro, isCancel, log, outro, select } from '@clack/prompts'
import dotenv from 'dotenv'
import { isEmpty } from 'lodash-es'
import { $, usePowerShell } from 'zx'

if (os.platform() === 'win32') {
  usePowerShell()
}

const CWD = process.cwd()
const PACKAGE = createRequire(import.meta.url)(path.join(CWD, 'package.json'))

const platformOptions = [
  { label: 'h5', value: { name: 'h5', args: [] }, hint: 'H5' },
  { label: 'mp-alipay', value: { name: 'mp-alipay', args: ['-p', 'mp-alipay'] }, hint: '支付宝小程序' },
  { label: 'mp-weixin', value: { name: 'mp-weixin', args: ['-p', 'mp-weixin'] }, hint: '微信小程序' },
  { label: 'mp-kuaishou', value: { name: 'mp-kuaishou', args: ['-p', 'mp-kuaishou'] }, hint: '快手小程序' },
  { label: 'mp-toutiao', value: { name: 'mp-toutiao', args: ['-p', 'mp-toutiao'] }, hint: '抖音小程序' },
]

function cancelGuard(x) {
  if (isCancel(x)) {
    cancel('操作取消')
    process.exit(0)
  }
}

try {
  intro(`MDM 租赁小程序 v${PACKAGE.version}`)

  /* 用户交互 */

  // 运行模式
  const runMode = await select({
    message: '选择运行模式',
    options: [
      { label: '开发', value: 'dev' },
      { label: '打包', value: 'build' },
    ],
  })
  cancelGuard(runMode)

  // 机构项目（从 env 目录读取）
  const viteModeOptions = await (async () => {
    const envFiles = (await fsp.readdir('env')).filter(x => x.startsWith('.env.'))
    const options = []
    for (const fileName of envFiles) {
      const fileContent = await fsp.readFile(path.join(CWD, 'env', fileName), 'utf8')
      const envFileContent = dotenv.parse(fileContent)

      options.push({
        label: envFileContent.X_NAME,
        value: {
          name: /^\.env\.(.+)$/.exec(fileName)[1],
          platforms: envFileContent.X_PLATFORMS.split(',').filter(x => platformOptions.map(y => y.label).includes(x)),
          theme: envFileContent.VITE_THEME,
        },
        hint: fileName,
      })
    }
    return options
  })()
  const viteMode = await select({
    message: '选择机构项目',
    options: viteModeOptions,
  })
  cancelGuard(viteMode)

  // 编译平台
  const platform = await select({
    message: '选择编译平台',
    options: platformOptions.filter(x => viteMode.platforms.includes(x.value.name)),
  })
  cancelGuard(platform)

  /* 不同主题文件合并 */

  // 删除静态资源目录
  await fsp.rm(path.join(CWD, 'src', 'static'), { recursive: true, force: true })

  const mergePaths = await (async () => {
    const publicFiles = (await fsp.readdir(path.join(CWD, 'theme_static', 'public'), { recursive: true }))
      .map(x => path.join('public', x))
    const themeFiles = (await fsp.readdir(path.join(CWD, 'theme_static', viteMode.theme), { recursive: true }))
      .map(x => path.join(viteMode.theme, x))

    // console.log('publicFiles', publicFiles)
    // console.log('themeFiles', themeFiles)

    const paths = [...publicFiles, ...themeFiles]
      .filter(x => !x.endsWith('.DS_Store'))
      .filter(x => fs.statSync(path.join(CWD, 'theme_static', x)).isFile())

    // console.log('paths', paths)

    return paths
  })()

  // 复制合并的文件
  const newDirs = (() => {
    const list = []
    for (const filePath of mergePaths) {
      const dirName = path.dirname(filePath)
      const usefulDirNames = dirName.split(path.sep).slice(1)
      if (!isEmpty(usefulDirNames)) {
        list.push(JSON.stringify(usefulDirNames))
      }
    }
    return [...new Set(list)].map(x => JSON.parse(x))
  })()
  console.log('newDirs', newDirs)
  for (const dir of newDirs) {
    await fsp.mkdir(path.join(CWD, 'src', 'static', ...dir), { recursive: true })
  }
  // process.exit(0)

  for (const filePath of mergePaths) {
    await fsp.copyFile(
      path.join(CWD, 'theme_static', filePath),
      path.join(CWD, 'src', 'static', ...filePath.split(path.sep).slice(1)),
    )
  }
}
catch (error) {
  console.error(error)
}
